package de.eeb;

import de.eeb.common.SBException;
import de.unikoeln.sharedbucks.R;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class RegisterUserActivity extends Activity {

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register_user);

		Button btnActivity = (Button) findViewById(R.id.do_register_user);

		btnActivity.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				EditText userEmailText = (EditText) findViewById(R.id.user_email);
				EditText userNameText = (EditText) findViewById(R.id.user_name);
				EditText userNumberText = (EditText) findViewById(R.id.user_telephone_number);
				
				try {
					if(!MainViewActivity.SBController.isUser(userNumberText.getText().toString())) {
						MainViewActivity.SBController.registerUser( userNumberText.getText().toString(), 
																userNameText.getText().toString(), 
																userEmailText.getText().toString());
						Log.d(RegisterUserActivity.class.getName(), "Registered at web service: " + userNumberText.getText().toString());
					} else {
						Log.d(RegisterUserActivity.class.getName(), "User already registered at web service: " + userNumberText.getText().toString());
					}
				} catch (SBException e) {
					Log.e(RegisterUserActivity.class.getName(), e.getMessage());
				}
				
				SharedPreferences settings = getSharedPreferences(MainViewActivity.PREFS_NAME, 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.putString("OwnNumber", userNumberText.getText().toString());
				
				if(editor.commit()) {
					Log.d(RegisterUserActivity.class.getName(), "Saved own number: " + userNumberText.getText().toString());
				} else {
					Log.e(RegisterUserActivity.class.getName(), "Cannot store own number in preferences: " + userNumberText.getText().toString());
				}

				
				Intent in = new Intent(RegisterUserActivity.this, MainViewActivity.class);
				startActivity(in);
				
			}
		});

	}

}